package com.miplus.ccrm.core.api.filetrans;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.miplus.ccrm.core.api.filetrans.model.FileTransResponseResult;
import com.miplus.ccrm.core.api.filetrans.sub.GetFileTrans;

import java.util.ArrayList;
import java.util.List;

public class FileTransApi {
    private static final String ACCESS_KEY_ID = "LTAI5tAT9Dq1yBVQhJT1nXFW";
    private static final String ACCESS_KEY_SECRET = "xEia8iwhvxfxKAKnl7kPtK16nFrPX2";
    private static final String APP_KEY = "80uMxWNCRpucZXRX";

    public static FileTransResponseResult processFileTrans(String fileLink) {
        GetFileTrans demo = new GetFileTrans(ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 提交录音文件识别请求，获取任务 ID
        String taskId = demo.submitFileTransRequest(APP_KEY, fileLink);
        if (taskId == null) {
            return null;
        }
        // 根据任务 ID 轮询识别结果
        String result = demo.getFileTransResult(taskId);
        if (result == null) {
            return null;
        }
        FileTransResponseResult fileTransResult = new FileTransResponseResult();
        //fileTransResult.setTaskId(taskId);
        //fileTransResult.setResult(result);
        // 解析识别结果，提取说话人、说话时间和内容
        JSONObject resultObj = JSONObject.parseObject(result);
        JSONArray sentencesArray = resultObj.getJSONArray("Sentences");
        List<FileTransResponseResult.SentenceInfo> sentenceInfos = new ArrayList<>();
        for (int i = 0; i < sentencesArray.size(); i++) {
            JSONObject sentence = sentencesArray.getJSONObject(i);
            FileTransResponseResult.SentenceInfo sentenceInfo = new FileTransResponseResult.SentenceInfo();
            sentenceInfo.setSpeakerId(sentence.getString("SpeakerId"));
            sentenceInfo.setBeginTime(sentence.getIntValue("BeginTime"));
            sentenceInfo.setEndTime(sentence.getIntValue("EndTime"));
            sentenceInfo.setText(sentence.getString("Text"));
            sentenceInfo.setSilenceDuration(sentence.getIntValue("SilenceDuration"));
            sentenceInfo.setChannelId(sentence.getIntValue("ChannelId"));
            sentenceInfo.setSpeechRate(sentence.getIntValue("SpeechRate"));
            sentenceInfo.setEmotionValue(sentence.getIntValue("EmotionValue"));
            sentenceInfos.add(sentenceInfo);
        }
        fileTransResult.setSentenceInfos(sentenceInfos);

        return fileTransResult;
    }
}
